import 'package:check_app/dao/input_dao.dart';
import 'package:check_app/dao/task_dao.dart';
import 'package:check_app/model/taskInfo.dart';
import 'package:check_app/page/CollectDetailPage.dart';
import 'package:check_app/page/InputPage.dart';
import 'package:check_app/scoped_model/app_model.dart';
import 'package:check_app/util/pref_util.dart';
import 'package:check_app/util/uploadImage_util.dart';
import 'package:flutter/material.dart';
import 'package:check_app/page/TaskDetailPage.dart';
import 'package:check_app/widgets/ToolsList.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:scoped_model/scoped_model.dart';
import 'dart:convert' as convert;

class TaskPage extends StatefulWidget {
  final int id;
  final String code;
  const TaskPage({Key key, this.id, this.code}) : super(key: key);
  @override
  State<StatefulWidget> createState() => new _TaskPageState();
}

class _TaskPageState extends State<TaskPage> {
  bool _loading = false;
  int id;
  int customerId;
  int guideBookId;
  String type;
  String code;
  String status = 'FINISH';
  String customerName;
  String guideBookName;
  String contractNo;
  String provinceName;
  String provinceCode;
  String cityName;
  String cityCode;
  String countyName;
  String countyCode;
  int checkQuantity;
  List operatorList;
  List proofUrlList;
  List toolsList = [];

  @override
  void initState() {
    super.initState();
    id = widget.id;

    getData();
  }

  Future<Null> getData() async {
    final taskInfo = await PrefUtil().getString('task_' + id.toString());
    if (taskInfo != null) {
      getLocalData();
      return null;
    }
    setState(() {
      _loading = true;
    });
    try {
      var result = await TaskDao.fetchTaskInfoFull(
          '/app/task/' + id.toString() + '/full');
      setState(() {
        _loading = false;
      });
      if (result.success) {
        setState(() {
          id = result.data.id;
          type = result.data.type;
          code = result.data.code;
          status = result.data.status;
          customerId = result.data.customerId;
          customerName = result.data.customerName;
          guideBookId = result.data.guideBookId;
          guideBookName = result.data.guideBookName;
          checkQuantity = result.data.checkQuantity;
          operatorList = result.data.operatorList;
          proofUrlList = result.data.proofUrlList;
          toolsList = result.data.subjectCollectList;
          contractNo = result.data.contractNo;
          provinceName = result.data.provinceName;
          provinceCode = result.data.provinceCode;
          cityName = result.data.cityName;
          cityCode = result.data.cityCode;
          countyName = result.data.countyName;
          countyCode = result.data.countyCode;
        });
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
    return null;
  }

  Future<Null> getLocalData() async {
    final taskInfo = await PrefUtil().getString('task_' + id.toString());
    final taskInfoModel = TaskInfo.fromJson(convert.jsonDecode(taskInfo));
    setState(() {
      id = taskInfoModel.id;
      type = taskInfoModel.type;
      code = taskInfoModel.code;
      status = taskInfoModel.status;
      customerId = taskInfoModel.customerId;
      customerName = taskInfoModel.customerName;
      guideBookId = taskInfoModel.guideBookId;
      guideBookName = taskInfoModel.guideBookName;
      checkQuantity = taskInfoModel.checkQuantity;
      operatorList = taskInfoModel.operatorList;
      proofUrlList = taskInfoModel.proofUrlList;
      toolsList = taskInfoModel.subjectCollectList;
      contractNo = taskInfoModel.contractNo;
      provinceName = taskInfoModel.provinceName;
      cityName = taskInfoModel.cityName;
      countyName = taskInfoModel.countyName;
    });
    return null;
  }

  Future<Null> submit() async {
    setState(() {
      _loading = true;
    });
    try {
      var result = await TaskDao.submit({
        'id': id.toString(),
      });
      setState(() {
        _loading = false;
      });
      if (result.success) {
        await PrefUtil().delete('task_' + id.toString());
        Navigator.of(context).pop();
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
      setState(() {
        _loading = false;
      });
    }
    return null;
  }

  Future<Null> saveProofUrlList(taskInfoMap) async {
    final proofUrlList =
        await UploadImageUtil().getImageNetUrl(taskInfoMap['proofUrlList']);
    taskInfoMap['proofUrlList'] = proofUrlList;
    await PrefUtil()
        .setString('task_' + id.toString(), convert.jsonEncode(taskInfoMap));
    try {
      final result = await TaskDao.editNormalTask({
        "id": widget.id.toString(),
        "proofUrlList": proofUrlList,
      });
      if (result.success) {
        print('success');
      } else {
        Fluttertoast.showToast(
          msg: result.message,
        );
      }
    } catch (e) {
      print(e);
    }
  }

  Future<Null> saveInputDate(taskInfoMap) async {
    for (var item in taskInfoMap['subjectCollectList']) {
      for (var innerItem in item['subjectList']) {
        if (innerItem['picUrlList'] != null) {
          final picUrlList =
              await UploadImageUtil().getImageNetUrl(innerItem['picUrlList']);
          innerItem['picUrlList'] = picUrlList;
          await PrefUtil().setString(
              'task_' + id.toString(), convert.jsonEncode(taskInfoMap));
        }
      }
      try {
        var result = await InputDao.batchSave({
          'collectId': item['id'],
          'subjectList': item['subjectList'],
        });
        setState(() {
          _loading = false;
        });
        if (result.success) {
          print('inputData success');
        } else {
          Fluttertoast.showToast(
            msg: result.message,
          );
        }
      } catch (e) {
        print(e);
      }
    }
  }

  Future<Null> submitFromLocal() async {
    setState(() {
      _loading = true;
    });
    final taskInfo = await PrefUtil().getString('task_' + id.toString());
    final taskInfoMap = convert.jsonDecode(taskInfo);
    // 提交原始凭证图片
    await saveProofUrlList(taskInfoMap);
    // 提交录入数据
    await saveInputDate(taskInfoMap);
    // 提交任务
    await submit();
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text(widget.code),
        actions: <Widget>[
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () async {
              final taskInfo =
                  await PrefUtil().getString('task_' + id.toString());
              if (taskInfo != null) {
                print('本地有数据');
                final taskInfoModel =
                    TaskInfo.fromJson(convert.jsonDecode(taskInfo));
                await Navigator.of(context)
                    .push(MaterialPageRoute(builder: (_) {
                  return TaskDetailPage(
                    id: taskInfoModel.id,
                    type: taskInfoModel.type,
                    code: taskInfoModel.code,
                    contractNo: taskInfoModel.contractNo,
                    status: taskInfoModel.status,
                    customerId: taskInfoModel.customerId,
                    customerName: taskInfoModel.customerName,
                    guideBookId: taskInfoModel.guideBookId,
                    guideBookName: taskInfoModel.guideBookName,
                    checkQuantity: taskInfoModel.checkQuantity,
                    operatorList: taskInfoModel.operatorList,
                    proofUrlList: taskInfoModel.proofUrlList,
                    provinceName: taskInfoModel.provinceName,
                    provinceCode: taskInfoModel.provinceCode,
                    cityName: taskInfoModel.cityName,
                    cityCode: taskInfoModel.cityCode,
                    countyName: taskInfoModel.countyName,
                    countyCode: taskInfoModel.countyCode,
                  );
                }));
                getData();
              } else {
                await Navigator.of(context)
                    .push(MaterialPageRoute(builder: (_) {
                  return TaskDetailPage(
                    id: id,
                    type: type,
                    code: code,
                    contractNo: contractNo,
                    status: status,
                    customerId: customerId,
                    customerName: customerName,
                    guideBookId: guideBookId,
                    guideBookName: guideBookName,
                    checkQuantity: checkQuantity,
                    operatorList: operatorList,
                    proofUrlList: proofUrlList,
                    provinceName: provinceName,
                    provinceCode: provinceCode,
                    cityName: cityName,
                    cityCode: cityCode,
                    countyName: countyName,
                    countyCode: countyCode,
                  );
                }));
                getData();
              }
            },
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.fromLTRB(20, 0, 20, 0),
              child: Text('详情'),
            ),
          ),
        ],
      ),
      body: SafeArea(
        child: Stack(
          children: <Widget>[
            ToolsList(
              toolsList: toolsList,
              onclick: (obj) async {
                print(obj);
                if (status != 'FINISH') {
                  final taskInfo =
                      await PrefUtil().getString('task_' + id.toString());
                  if (taskInfo != null) {
                    print('本地有数据');
                    final taskInfoModel =
                        TaskInfo.fromJson(convert.jsonDecode(taskInfo));
                    final result = await Navigator.of(context)
                        .push(MaterialPageRoute(builder: (_) {
                      return InputPage(
                        taskId: id,
                        index: obj['index'],
                        id: obj['item'].id,
                        code: obj['item'].code,
                        totalNumber: obj['item'].planQuantity,
                        finishQuantity: taskInfoModel
                            .subjectCollectList[obj['index']].finishQuantity,
                        subjectList: taskInfoModel
                            .subjectCollectList[obj['index']].subjectList,
                      );
                    }));
                    getLocalData();
                  } else {
                    print('本地无数据');
                    final result = await Navigator.of(context)
                        .push(MaterialPageRoute(builder: (_) {
                      return InputPage(
                        taskId: id,
                        index: obj['index'],
                        id: obj['item'].id,
                        code: obj['item'].code,
                        totalNumber: obj['item'].planQuantity,
                        finishQuantity: obj['item'].finishQuantity,
                        subjectList: obj['item'].subjectList,
                      );
                    }));
                    final taskInfo =
                        await PrefUtil().getString('task_' + id.toString());
                    if (taskInfo != null) {
                      getLocalData();
                    } else {
                      getData();
                    }
                  }
                } else {
                  Navigator.of(context).push(MaterialPageRoute(builder: (_) {
                    return CollectDetailPage(id: obj['item'].id);
                  }));
                }
              },
            ),
            status != 'FINISH'
                ? Positioned(
                    right: 16,
                    bottom: 112,
                    child: GestureDetector(
                      onTap: () async {
                        final taskInfo =
                            await PrefUtil().getString('task_' + id.toString());
                        if (taskInfo != null) {
                          print('本地有数据');
                          final taskInfoModel =
                              TaskInfo.fromJson(convert.jsonDecode(taskInfo));
                          await Navigator.of(context)
                              .push(MaterialPageRoute(builder: (_) {
                            return TaskDetailPage(
                              id: taskInfoModel.id,
                              type: taskInfoModel.type,
                              code: taskInfoModel.code,
                              contractNo: taskInfoModel.contractNo,
                              status: taskInfoModel.status,
                              customerId: taskInfoModel.customerId,
                              customerName: taskInfoModel.customerName,
                              guideBookId: taskInfoModel.guideBookId,
                              guideBookName: taskInfoModel.guideBookName,
                              checkQuantity: taskInfoModel.checkQuantity,
                              operatorList: taskInfoModel.operatorList,
                              proofUrlList: taskInfoModel.proofUrlList,
                              provinceName: taskInfoModel.provinceName,
                              provinceCode: taskInfoModel.provinceCode,
                              cityName: taskInfoModel.cityName,
                              cityCode: taskInfoModel.cityCode,
                              countyName: taskInfoModel.countyName,
                              countyCode: taskInfoModel.countyCode,
                            );
                          }));
                          getData();
                        } else {
                          await Navigator.of(context)
                              .push(MaterialPageRoute(builder: (_) {
                            return TaskDetailPage(
                              id: id,
                              type: type,
                              code: code,
                              contractNo: contractNo,
                              status: status,
                              customerId: customerId,
                              customerName: customerName,
                              guideBookId: guideBookId,
                              guideBookName: guideBookName,
                              checkQuantity: checkQuantity,
                              operatorList: operatorList,
                              proofUrlList: proofUrlList,
                              provinceName: provinceName,
                              provinceCode: provinceCode,
                              cityName: cityName,
                              cityCode: cityCode,
                              countyName: countyName,
                              countyCode: countyCode,
                            );
                          }));
                          getData();
                        }
                      },
                      child: Container(
                        width: 44,
                        height: 44,
                        alignment: Alignment.center,
                        padding: EdgeInsets.only(top: 6),
                        decoration: BoxDecoration(
                          color: Color.fromRGBO(89, 131, 252, 1),
                          borderRadius: BorderRadius.circular(22),
                        ),
                        child: Column(
                          children: <Widget>[
                            Text(
                              '原始',
                              style: TextStyle(
                                fontSize: 11,
                                height: 15 / 11,
                                color: Colors.white,
                              ),
                            ),
                            Text(
                              '凭证',
                              style: TextStyle(
                                fontSize: 11,
                                height: 15 / 11,
                                color: Colors.white,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  )
                : SizedBox(),
            status != 'FINISH'
                ? Positioned(
                    left: 0,
                    right: 0,
                    bottom: 24,
                    child: Container(
                      padding: EdgeInsets.fromLTRB(16, 0, 16, 0),
                      width: double.infinity,
                      child: MaterialButton(
                        onPressed: () async {
                          print('提交');
                          final result = await PrefUtil()
                              .openAlertDialog(context, '完成提交后，该任务不可新增待检物');
                          if (result == 'ok') {
                            final taskInfo = await PrefUtil()
                                .getString('task_' + id.toString());
                            if (taskInfo != null) {
                              submitFromLocal();
                            } else {
                              submit();
                            }
                          }
                        },
                        color: Colors.blue,
                        textColor: Colors.white,
                        height: 44,
                        child: Text(
                          '提交',
                          style: TextStyle(
                            fontSize: 14,
                            height: 24 / 17,
                          ),
                        ),
                      ),
                    ),
                  )
                : SizedBox(),
          ],
        ),
      ),
    );
  }
}
